/* 
 * $Id: AlternativeNode.java 1259 2007-01-09 14:23:47Z tcoupaye $
 *
 * Behavior Protocols extensions for static and runtime checking
 * developed for the Julia implementation of Fractal.
 *
 * Copyright 2004
 *    Distributed Systems Research Group
 *    Department of Software Engineering
 *    Faculty of Mathematics and Physics
 *    Charles University, Prague
 *
 * Copyright (C) 2006
 *    Formal Methods In Software Engineering Group
 *    Institute of Computer Science
 *    Academy of Sciences of the Czech Republic
 *
 * Copyright (C) 2006 France Telecom
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 *
 * Contact: ft@nenya.ms.mff.cuni.cz
 * Authors: Jan Kofron <kofron@nenya.ms.mff.cuni.cz>
 */


package org.objectweb.fractal.bpc.checker.node;

import java.util.ArrayList;

import org.objectweb.fractal.bpc.checker.DFSR.CheckingException;
import org.objectweb.fractal.bpc.checker.state.*;
import org.objectweb.fractal.bpc.checker.utils.AnotatedProtocol;


/**
 * Alternative node represent the alternative operator.
 */
public class AlternativeNode extends TreeNode {

    /** Creates a new instance of AlternativeNode */
    public AlternativeNode(TreeNode[] nodes) {
        super(getProtocol(nodes));
        this.nodes = nodes;

        isorparallel = false;
        initState = null;
    }

    /**
     * 
     * @see org.objectweb.fractal.bpc.checker.node.TreeNode#getInitial()
     */
    public State getInitial() {
        if (initState == null) {
            /*
             * State[] states = new State[nodes.length]; for (int i = 0; i <
             * states.length; ++i) states[i] = nodes[i].getInitial();
             */
            initState = new DenotedState(-1, new SimpleState(0), logchildrencnt, this);
        }

        return initState;
    }
    
    /**
     * @return accepting state - useful as heuristics for creating state signatures
     */
    public State getAccepting() {
        return new DenotedState(-2, new SimpleState(0), logchildrencnt, this);
        
    }

    /**
     * 
     * @see org.objectweb.fractal.bpc.checker.node.TreeNode#isAccepting(org.objectweb.fractal.bpc.checker.state.State)
     */
    public boolean isAccepting(State state) {
        int index = ((DenotedState) state).index;

        if (index == -1) {
            for (int i = 0; i < nodes.length; ++i)
                if (nodes[i].isAccepting(nodes[i].getInitial()))
                    return true;

            return false;
        } else {
            return (index == -2) || (nodes[index].isAccepting(((DenotedState) state).state));
        }

    }

    /**
     * 
     * @see org.objectweb.fractal.bpc.checker.node.TreeNode#getTransitions(org.objectweb.fractal.bpc.checker.state.State)
     */
    public TransitionPairs getTransitions(State state) throws InvalidParameterException, CheckingException {
        DenotedState dstate = (DenotedState) state;
        int stindex = dstate.index;
        int nodecnt = nodes.length;
        int totallen = 0;
        
        if (stindex == -2)
            return new TransitionPairs(new TransitionPair[0]);

        if (stindex == -1) {
            TransitionPair[][] trans = new TransitionPair[nodecnt][];

            for (int i = 0; i < nodecnt; ++i) {
                trans[i] = nodes[i].getTransitions(nodes[i].getInitial()).transitions;
                totallen += trans[i].length;
            }

            TransitionPair[] result = new TransitionPair[totallen];

            for (int i = 0, idx = 0; idx < nodecnt; ++idx) {
                for (int j = 0; j < trans[idx].length; ++j, ++i) {

                    State newstate = trans[idx][j].state;
                    result[i] = new TransitionPair(trans[idx][j].eventIndex, new DenotedState(idx, newstate, logchildrencnt, this));
                }
            }

            return new TransitionPairs(result);

        } else {

            TransitionPair[] nodetrans = nodes[stindex].getTransitions(dstate.state).transitions;
            //int nodelen = nodetrans.length;
            TransitionPair[] trans = new TransitionPair[nodetrans.length];

            for (int i = 0; i < nodetrans.length; ++i)
                trans[i] = new TransitionPair(nodetrans[i].eventIndex, new DenotedState(stindex, nodetrans[i].state, logchildrencnt, this));

            return new TransitionPairs(trans);
        }
    }

    /**
     * @see org.objectweb.fractal.bpc.checker.node.TreeNode#getWeight()
     */
    public long getWeight() {
        if (weight != -1)
            return weight;
        else {
            long weight = 0;
            for (int i = 0; i < nodes.length; ++i)
                weight += nodes[i].getWeight();

            return weight;
        }
    }

    /**
     * @return the symbolic name of the treenode denoting its type
     */
    public String[] getTypeName() {
        String[] result = { "Alternative", "+" };
        return result;
    }

    /**
     * Overrides the default implementation, because of the non-determinism that
     * must be handled here. This is one of the only two places where
     * non-determinism can inherently appear.
     * 
     * @return number of bits needed to keep the determinized signature of this
     *         subtree
     */
    public int getLeafCount() {
        int cnt = 0;
        for (int i = 0; i < nodes.length; ++i)
            cnt += nodes[i].getLeafCount();

        int max = 0;
        for (int i = 0; i < 32; ++i) {
            if ((nodes.length >>> i) == 0) {
                max = i;
                break;
            }
        }

        this.logchildrencnt = max;

        // adding the space necessary for identifying a child
        // and assume that all of the children transition may start
        // with the same transition
        cnt += (nodes.length * max);

        return cnt;
    }

    /**
     * Sets the orparallel operator bit needed for protocol inverting.
     */
    public void setorparallel() {
        isorparallel = true;
    }

    /**
     * @return the orparallel bit
     */
    public boolean getorparallel() {
        return isorparallel;
    }

    /**
     * @see org.objectweb.fractal.bpc.checker.node.TreeNode#getAnotatedProtocol(org.objectweb.fractal.bpc.checker.state.State)
     */
    public AnotatedProtocol getAnotatedProtocol(State state) {
        DenotedState dstate = (DenotedState) state;
        int nodecnt = nodes.length;
        String result = new String();
        ArrayList indicesresult = new ArrayList();
        
        result = "(";
        for (int i = 0; i < nodecnt; ++i) {
            AnotatedProtocol subresult = nodes[i].getAnotatedProtocol(((dstate != null) && (dstate.index == i)) ? dstate.state : null);
            
            for (int j = 0; j < subresult.indices.size(); ++j)
                indicesresult.add(new Integer(((Integer)subresult.indices.get(j)).intValue() + result.length()));
            
            result += subresult.protocol;
            
            if (i < nodecnt - 1)
                result += ")+(";
        }
        result += ")";
        
        if ((dstate != null) && (dstate.index == -1))
            indicesresult.add(new Integer(0));
        
        return new AnotatedProtocol(result, indicesresult);
    }


    
    /**
     * This method is obsolete and used only for debuging, the protocol is
     * stored during the parse process.
     * 
     * @deprecated
     * @return the protocol of this tree.
     */
    static private String getProtocol(TreeNode[] nodes) {
        String result = new String();
        result = "(" + nodes[0].protocol + ")";

        for (int i = 1; i < nodes.length; ++i) {
            result += " + (" + nodes[i].protocol + ")";
        }

        return result;

    }

    //--------------------------------------------------------------------------
    /**
     * Initial state of the automaton
     */
    private DenotedState initState;

    /**
     * logarithm of child count
     */
    private int logchildrencnt;

    /**
     * true if this is an orparallel node
     */
    private boolean isorparallel;

}
